// File GameWorld.cpp
//
// Purpose: Contains all entities for the game
//
// Author : Bryson King
// Date : 21 March 2013
// --------------------------------------------------------------
#include "GameWorld.h"
#include "Terrorist.h"
#include "Player.h"
#include "GenericPerson.h"
#include "IPerson.h"
#include "EntityManager.h"

CGameWorld::CGameWorld() : m_pHeadOfList(new entity_node()), m_pTailOfList(m_pHeadOfList)
{
	// Create and add the known entities to the game world
	AddEntityToGameWorld(new CPlayer(ent_Player));
	AddEntityToGameWorld(new CTerrorist(ent_Terrorist));
}

CGameWorld::~CGameWorld()
{
	entity_node* tempNode;

	// Cycle through each node deleting each until the list is empty 
	while (m_pHeadOfList != nullptr)
	{
		tempNode = m_pHeadOfList;
		m_pHeadOfList = m_pHeadOfList->next;
		delete tempNode;
	}
}

void CGameWorld::AddEntityToGameWorld(CBaseGameEntity* entity)
{
	// Create the new node for the list
	entity_node* newNode = new entity_node();
	newNode->entity = entity;
	newNode->next = nullptr;

	// Add the node to the list
	m_pTailOfList->next = newNode;
	m_pTailOfList = newNode;

	// Add the entity to the entity manager
	EntityMgr->RegisterEntity(entity);
}

void CGameWorld::RemoveEntityFromGameWorld(CBaseGameEntity* entity)
{
	int entityID = entity->ID();
	entity_node* tempNode = m_pHeadOfList;
	entity_node* entityNode;

	// Remove the entity from the entity manager
	EntityMgr->RemoveEntity(entity);

	// Search the list for the node to delete
	while (tempNode->next != nullptr)
	{
		// If the node is found, remove the node and delete it
		if (tempNode->next->entity->ID() == entityID)
		{
			entityNode = tempNode->next;
			tempNode->next = tempNode->next->next;
			entityNode->next = nullptr;
			delete entityNode->entity;
			delete entityNode;
			break;
		}
	}
}

void CGameWorld::UpdateGameWorld()
{
	entity_node* tempNode = m_pHeadOfList->next;

	// Cycle through each node calling the Update function for the entity 
	while (tempNode != nullptr)
	{
		tempNode->entity->Update();
		tempNode = tempNode->next;
	}
}
